#ifndef WEATHERMANAGER_H
#define WEATHERMANAGER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTimer>
#include <QString>
#include <QStringList>
#include <QHash>

class WeatherManager : public QObject
{
    Q_OBJECT

public:
    struct WeatherData {
        QString city;
        QString weather;
        QString temperature;
        QString humidity;
        QString windSpeed;
        QString windDirection;
        QString pressure;
        QString visibility;
        QString updateTime;
        bool isValid;
        
        WeatherData() : isValid(false) {}
    };

    explicit WeatherManager(QObject *parent = nullptr);
    ~WeatherManager();

    // 获取当前城市
    QString getCurrentCity() const { return m_currentCity; }
    
    // 设置城市并获取天气数据
    void setCity(const QString &city);
    
    // 获取支持的城市列表
    QStringList getSupportedCities() const { return m_supportedCities; }
    
    // 获取当前天气数据
    WeatherData getCurrentWeatherData() const { return m_currentWeatherData; }
    
    // 手动刷新天气数据
    void refreshWeatherData();
    
    // 启动/停止自动更新
    void startAutoUpdate(int intervalMinutes = 30);
    void stopAutoUpdate();

    // 通过城市名获取和风天气location id
    QString getCityId(const QString &city) const;

    // 加载城市到id的映射表
    void initializeCityIdMap();

signals:
    void weatherDataUpdated(const WeatherData &data);
    void cityChanged(const QString &city);
    void errorOccurred(const QString &error);

private slots:
    void onNetworkReplyFinished();
    void onAutoUpdateTimer();

private:
    void fetchWeatherData();
    void parseWeatherData(const QByteArray &data);
    void setupSupportedCities();
    void simulateWeatherData();

    QNetworkAccessManager *m_networkManager;
    QNetworkReply *m_currentReply;
    QTimer *m_autoUpdateTimer;
    
    QString m_currentCity;
    WeatherData m_currentWeatherData;
    QStringList m_supportedCities;
    
    // API配置
    QString m_apiKey;
    QString m_apiUrl;
    
    // 城市名 -> location id 映射(和风天气)
    QHash<QString, QString> m_cityIdMap;
    
    static const int DEFAULT_TIMEOUT = 10000; // 10秒超时
};

#endif // WEATHERMANAGER_H 